
#include <stdio.h>
#include <unistd.h>			// alarm()
#include <signal.h>			// signal() and SIG definitions

#define TRUE 1
#define FALSE 0

int stop = FALSE;			// flag signalling to stop; set by signal handler

// Prototypes
void timeout_handler(int sig); 		// timer handler: just sets the stop flag
int isPrime(int n);            		// determines if n is prime, periodically checking the timeout flag
int largestPrime(int timeout);		// finds the largest prime (starting with 1) in time available


int main(int argc, char **argv)
{
	int t;
	for(t = 5; t <= 15; t += 5) {
		int prime;
		printf("largestPrime(timeout = %d) ... ", t);
		fflush(stdout);

		prime = largestPrime(t);

		printf("result: %d\n", prime);
	}

	return 0;
}

int isPrime(int n)
{
	int maxDiv = n / 2;
	int div;

	for(div = 2; div < maxDiv; div++) {
		if(n%div == 0)
			return FALSE;

		//check the stop flag once in a while
		if(stop)
			return FALSE;
	}

	return TRUE;
}

int largestPrime(int timeout)
{
	int n;
	int largest;

	stop = FALSE;						// reset the stop flag
	signal(SIGALRM, timeout_handler);	// set the signal handler. note: this needs to be done every time
	alarm(timeout);						// start the timer

	for(largest = n = 2;; n++) {
		// check the stop flag once in a while
		if(stop)
			break;

		if(isPrime(n))
			largest = n;
	}

	return largest;
}

void timeout_handler(int sig)
{
	stop = TRUE;
	printf("timeout\n");
	fflush(stdout);
}
